<template>
  <div class="container main-fade-in">
    <!-- 云朵元素 -->
    <div class="cloud-1"></div>
    <div class="cloud-2"></div>
    <div class="cloud-3"></div>
    
    <div class="content-wrapper">
      <!-- 使用搜索框组件 -->
      <SearchBox />
      <!-- 已保存城市列表 -->
      <transition-group name="city-fade" tag="div" class="city-list">
        <div 
          class="add-city city-card-glass"
          v-for="(city, index) in savedCities"
          :key="city.adcode"
          @mouseenter="showButtons = index"
          @mouseleave="showButtons = -1"
        >
          <div class="a1">
            <div class="addleft">
              <h3>{{ city.name }}</h3>
              <span>{{ city.temp }}度</span>
            </div>
            <div class="button-city" v-show="showButtons === index">
              <button class="btn-animate" @click="$router.push({ name: 'CityView', params: { adcode: city.adcode } })">查看</button>
              <button class="btn-animate" @click="deleteCity(city.adcode)">删除</button>
            </div>
          </div>
        </div>
      </transition-group>
      <!-- 空状态提示 -->
      <div class="empty-message fade-in" v-show="!hasSavedCities">
        <p>暂时没有保存过城市天气信息，请查询后点击右上角"+"号保存。</p>
      </div>
      <h2>近期天气</h2>
      <div class="forecast-section fade-in">
        <div class="forecast-cards">
          <transition-group name="forecast-fade" tag="div" class="forecast-list">
            <div 
              class="forecast-card card-glass"
              v-for="(day, index) in forecastCards"
              :key="index"
            >
              <span class="day">{{ formatDay(index, day.week) }}</span>
              <span class="date">{{ formatDate(day.date) }}</span>
              <span class="weather-type">{{ day.dayweather }}</span>
              <span class="wind">风力 {{ day.daypower }}级</span>
            </div>
          </transition-group>
        </div>
        <div class="temperature-chart fade-in">
          <v-chart class="chart" :option="option" autoresize />
        </div>
        <div class="charts-row">
          <div class="pie-chart">
            <v-chart class="chart" :option="pieOption" autoresize />
          </div>
          <div class="bar-chart">
            <v-chart class="chart" :option="barOption" autoresize />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed,  onBeforeUnmount } from 'vue'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart } from 'echarts/charts'
import { GridComponent } from 'echarts/components'


import SearchBox from '@/components/SearchBox.vue'
import { getWeatherForecast } from '@/api/weatherApi'

use([CanvasRenderer, LineChart, GridComponent])

const showSearchResults = ref(false);

// 控制按钮显示
const showButtons = ref(false);
// 控制是否显示已保存城市列表
const hasSavedCities = ref(true); 



// const searchCity = ref('武汉')
const forecastData = ref(null)

// 图表配置
const option = ref({
  grid: {
    left: '5%',
    right: '5%',
    top: '5%',
    bottom: '5%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: [],
    show: false,
  },
  yAxis: {
    type: 'value',
    show: false,
    min: function (value) {
      return Math.floor(value.min * 0.1)
    }
  },
  series: [
    {
      name: '白天',
      type: 'line',
      data: [],
      symbolSize: 8,
      symbol: 'circle',
      smooth: true,
      lineStyle: { width: 3, color: '#7EB3FF' },
      itemStyle: { color: '#7EB3FF', borderWidth: 2, borderColor: '#fff' },
      label: {
        show: true,
        position: 'top',
        formatter: '白{c}°C',
        color: '#FFFFFF',
        fontSize: 12,
        padding: [2, 4],
        distance: 6
      }
    },
    {
      name: '夜间',
      type: 'line',
      data: [],
      symbolSize: 8,
      symbol: 'circle',
      smooth: true,
      lineStyle: { width: 3, color: '#A7E25F' },
      itemStyle: { color: '#A7E25F', borderWidth: 2, borderColor: '#fff' },
      label: {
        show: true,
        position: 'bottom',
        formatter: '晚{c}°C',
        color: '#FFFFFF',
        fontSize: 12,
        padding: [2, 4],
        distance: 6
      }
    }
  ]
})

// 处理日期显示
const formatDate = (dateStr) => {
  const date = new Date(dateStr)
  return `${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`
}

// 处理星期显示
const formatDay = (index, week) => {
  const weekMap = ['日', '一', '二', '三', '四', '五', '六']
  // 前两日特殊处理
  if (index === 0) return '今天';
  if (index === 1) return '明天';
  
  return `周${weekMap[week % 7] || ''}`;
}

// 计算属性处理预报卡片数据
const forecastCards = computed(() => {
  return forecastData.value?.casts?.map((cast, index) => ({
    ...cast,
    // 添加week字段格式化（如果API返回的是数字）
    week: cast.week || `周${index + 1}` 
  })).slice(0, 4) || []
})

// 获取天气数据
const fetchWeatherData = async () => {
  try {
    const data = await getWeatherForecast('武汉') // 固定使用武汉
    forecastData.value = data
    
    // 更新图表数据
    option.value.xAxis.data = forecastCards.value.map((_, index) => formatDay(index))
    option.value.series[0].data = forecastCards.value.map(d => parseInt(d.daytemp))
    option.value.series[1].data = forecastCards.value.map(d => parseInt(d.nighttemp))
    option.value.xAxis.data = forecastCards.value.map((day, index) => 
      formatDay(index, day.week) // 添加week参数
    )
    
  } catch (error) {
    console.error('获取天气数据失败:', error)
    forecastData.value = null
  }
}

// 初始化加载数据
onMounted(fetchWeatherData)

// 已保存城市列表
const savedCities = ref([]);

// 安全获取localStorage数据
const loadSavedCities = () => {
  try {
    const savedData = localStorage.getItem('savedCities');
    if (savedData) {
      const parsed = JSON.parse(savedData);
      savedCities.value = Array.isArray(parsed) ? parsed : [];
    } else {
      savedCities.value = [];
    }
    // 根据是否有保存的城市设置空状态显示
    hasSavedCities.value = savedCities.value.length > 0;
  } catch (error) {
    console.error('加载保存的城市失败:', error);
    savedCities.value = [];
    hasSavedCities.value = false;
  }
};



// 删除城市
const deleteCity = (adcode) => {
  savedCities.value = savedCities.value.filter(c => c.adcode !== adcode);
  localStorage.setItem('savedCities', JSON.stringify(savedCities.value));
  hasSavedCities.value = savedCities.value.length > 0;
  
  // 触发事件通知Header组件更新按钮状态
  window.dispatchEvent(new Event('storage-update'));
};

// // 初始化时加载
onMounted(() => {
  loadSavedCities();
  document.addEventListener('click', handleClickOutside);
  window.addEventListener('storage-update', loadSavedCities);
});

// 组件卸载时清理
onBeforeUnmount(() => {
  document.removeEventListener('click', handleClickOutside);
  window.removeEventListener('storage-update', loadSavedCities);
});

// 点击外部关闭搜索结果
const handleClickOutside = (event) => {
  const searchBox = document.querySelector('.search-box');
  if (searchBox && !searchBox.contains(event.target)) {
    showSearchResults.value = false;
  }
};

onMounted(() => {
  document.addEventListener('click', handleClickOutside);
});

onBeforeUnmount(() => {
  document.removeEventListener('click', handleClickOutside);
});

// 饼状图和柱状图数据逻辑

const pieOption = computed(() => {
  // 统计推荐类型的总权重
  let out = 0, inRoom = 0, shopping = 0, park = 0
  forecastCards.value.forEach(day => {
    const temp = parseInt(day.daytemp)
    const weather = day.dayweather
    if (weather.includes('雨')) {
      inRoom += 1
    } else if (temp >= 18 && temp <= 26) {
      out += 0.7
      inRoom += 0.1
      shopping += 0.2
    } else if (temp > 30) {
      inRoom += 0.6
      park += 0.3
      out += 0.1
    } else {
      inRoom += 1
    }
  })
  // 归一化为百分比
  const total = out + inRoom + shopping + park
  return {
    title: { text: '适合游玩类型', left: 'center', top: 10, textStyle: { color: '#fff', fontSize: 14 } },
    tooltip: { trigger: 'item', formatter: '{b}: {d}% ({c}天权重)' },
    legend: { bottom: 0, left: 'center', textStyle: { color: '#fff' } },
    series: [
      {
        name: '游玩类型',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        label: { show: true, color: '#fff', fontSize: 12, formatter: '{b}: {d}%' },
        labelLine: { show: true },
        data: [
          { value: out, name: '外出运动游玩' },
          { value: inRoom, name: '在家活动' },
          { value: shopping, name: '逛街' },
          { value: park, name: '公园避暑' }
        ]
      }
    ]
  }
})

const barOption = computed(() => {
  // 每天推荐类型
  return {
    title: { text: '每日游玩建议', left: 'center', top: 10, textStyle: { color: '#fff', fontSize: 14 } },
    tooltip: {},
    xAxis: {
      type: 'category',
      data: forecastCards.value.map((d, i) => `第${i+1}天`),
      axisLabel: { color: '#fff' }
    },
    yAxis: {
      type: 'value',
      minInterval: 1,
      axisLabel: { color: '#fff' }
    },
    series: [
      {
        data: forecastCards.value.map(day => {
          const temp = parseInt(day.daytemp)
          const weather = day.dayweather
          if (weather.includes('雨')) return 0 // 在家
          if (temp >= 18 && temp <= 26) return 1 // 外出运动游玩
          if (temp > 30) return 2 // 公园避暑
          if (temp > 10 && temp < 18) return 3 // 逛街
          return 0 // 其他情况在家
        }),
        type: 'bar',
        barWidth: '40%',
        itemStyle: {
          color: params => {
            if (params.value === 0) return '#2196f3' // 在家
            if (params.value === 1) return '#4caf50' // 外出
            if (params.value === 2) return '#ff9800' // 公园
            if (params.value === 3) return '#eab308' // 逛街
            return '#888'
          }
        },
        label: {
          show: true,
          position: 'top',
          color: '#fff',
          formatter: v => {
            if (v.value === 0) return '在家'
            if (v.value === 1) return '外出'
            if (v.value === 2) return '公园'
            if (v.value === 3) return '逛街'
            return ''
          }
        }
      }
    ]
  }
})

</script>

<style lang="scss" scoped>
.container {
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 40px;
  border-radius: 24px;
  box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.18);
  backdrop-filter: blur(8px);
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  position: relative;
  overflow: hidden;
  animation: fadeInUp 1s cubic-bezier(0.4,0,0.2,1);
  
  // 天气背景动画
  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: 
      radial-gradient(circle at 20% 50%, rgba(120, 119, 198, 0.3) 0%, transparent 50%),
      radial-gradient(circle at 80% 20%, rgba(255, 255, 255, 0.1) 0%, transparent 50%),
      radial-gradient(circle at 40% 80%, rgba(120, 119, 198, 0.2) 0%, transparent 50%);
    animation: weatherBg 20s ease-in-out infinite;
    z-index: 0;
  }
  
  // 云朵效果 - 优化为更真实的云朵形状
  &::after {
    content: '';
    position: absolute;
    top: 8%;
    left: -120px;
    width: 180px;
    height: 50px;
    background: rgba(255, 255, 255, 0.12);
    border-radius: 25px;
    animation: cloudMove 15s linear infinite;
    z-index: 1;
    
    // 添加云朵的圆形部分
    &::before {
      content: '';
      position: absolute;
      top: -20px;
      left: 30px;
      width: 45px;
      height: 45px;
      background: rgba(255, 255, 255, 0.12);
      border-radius: 50%;
    }
    
    &::after {
      content: '';
      position: absolute;
      top: -15px;
      right: 25px;
      width: 40px;
      height: 40px;
      background: rgba(255, 255, 255, 0.12);
      border-radius: 50%;
    }
  }
  
  // 添加更多云朵
  .cloud-1 {
    position: absolute;
    top: 15%;
    left: -150px;
    width: 120px;
    height: 40px;
    background: rgba(255, 255, 255, 0.08);
    border-radius: 20px;
    animation: cloudMove 12s linear infinite;
    z-index: 1;
    
    &::before {
      content: '';
      position: absolute;
      top: -15px;
      left: 20px;
      width: 40px;
      height: 40px;
      background: rgba(255, 255, 255, 0.08);
      border-radius: 50%;
    }
    
    &::after {
      content: '';
      position: absolute;
      top: -10px;
      right: 15px;
      width: 35px;
      height: 35px;
      background: rgba(255, 255, 255, 0.08);
      border-radius: 50%;
    }
  }
  
  .cloud-2 {
    position: absolute;
    top: 25%;
    left: -200px;
    width: 150px;
    height: 50px;
    background: rgba(255, 255, 255, 0.06);
    border-radius: 25px;
    animation: cloudMove 18s linear infinite;
    z-index: 1;
    
    &::before {
      content: '';
      position: absolute;
      top: -20px;
      left: 25px;
      width: 50px;
      height: 50px;
      background: rgba(255, 255, 255, 0.06);
      border-radius: 50%;
    }
    
    &::after {
      content: '';
      position: absolute;
      top: -15px;
      right: 20px;
      width: 45px;
      height: 45px;
      background: rgba(255, 255, 255, 0.06);
      border-radius: 50%;
    }
  }
  
  .cloud-3 {
    position: absolute;
    top: 35%;
    left: -180px;
    width: 100px;
    height: 35px;
    background: rgba(255, 255, 255, 0.05);
    border-radius: 17px;
    animation: cloudMove 20s linear infinite;
    z-index: 1;
    
    &::before {
      content: '';
      position: absolute;
      top: -12px;
      left: 15px;
      width: 30px;
      height: 30px;
      background: rgba(255, 255, 255, 0.05);
      border-radius: 50%;
    }
    
    &::after {
      content: '';
      position: absolute;
      top: -8px;
      right: 10px;
      width: 25px;
      height: 25px;
      background: rgba(255, 255, 255, 0.05);
      border-radius: 50%;
    }
  }
  
  .content-wrapper {
    width: 100%;
    margin: 0 auto;
    display: flex;
    flex-direction: column;
    align-items: center;
    position: relative;
    z-index: 2;
  }
  .city-list {
    width: 100%;
    display: flex;
    flex-direction: column;
    gap: 1rem;
    margin-bottom: 1.5rem;
  }
  .add-city {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
    min-width: 260px;
    max-width: 600px;
    margin: 0 auto;
    margin-top: 0;
    border-radius: 16px;
    box-shadow: 0 4px 24px 0 rgba(31, 38, 135, 0.18);
    background: rgba(255,255,255,0.08);
    backdrop-filter: blur(6px);
    opacity: 0;
    transform: translateY(30px);
    animation: fadeInUp 0.7s cubic-bezier(0.4,0,0.2,1) forwards;
    transition: box-shadow 0.3s, transform 0.3s;
    &.city-card-glass {
      opacity: 1;
      transition: box-shadow 0.3s, transform 0.3s;
      &:hover {
        box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.28);
        transform: scale(1.03) translateY(-2px);
        background: rgba(255,255,255,0.15);
      }
    }
    .a1{
      height: 44px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      width: 100%;
      .addleft{
        display: flex;
        flex-direction: row;
        align-items: flex-start;
        gap: 0.25rem;
        padding: 0.75rem 1rem;
        width: 100%;
        background-color: transparent;
        h3 {
          margin: 0;
          font-size: 1.1rem;
          font-weight: 500;
          word-break: break-all;
          max-width: 180px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
        span {
          font-size: 1rem;
          word-break: break-all;
        }
      }
      .button-city{
        display: flex;
        margin-bottom: 0;
        button{
          margin-left: 10px;
          height: 36px;
          text-align: center;
          opacity: 1;
          background-color: #eab308;
          width: 70px;
          cursor: pointer;
          font-family: inherit;
          font-size: 1rem;
          font-weight: 500;
          line-height: inherit;
          color: inherit;
          border: none;
          border-radius: 8px;
          box-shadow: 0 2px 8px rgba(0,0,0,0.08);
          transition: transform 0.15s, box-shadow 0.2s;
        }
        .btn-animate:active {
          transform: scale(0.92);
          box-shadow: 0 1px 2px rgba(0,0,0,0.12);
        }
      }
    }
  }
  h2 {
    margin: 2.5rem 0 1rem 0;
    font-size: 1.2rem;
    font-weight: 500;
    text-align: left;
    width: 100%;
    max-width: 600px;
    margin-left: auto;
    margin-right: auto;
  }
  .forecast-section {
    width: 100%;
    max-width: 900px;
    margin: 0 auto;
    border-radius: 16px;
    background: rgba(255,255,255,0.08);
    box-shadow: 0 2px 8px rgba(0,0,0,0.08);
    margin-top: 1.5rem;
    padding-bottom: 1.5rem;
    .forecast-cards {
      width: 100%;
      display: flex;
      justify-content: space-between;
      margin-bottom: 0;
      background-color: transparent;
      border-radius: 8px 8px 0 0;
      padding: 1.5rem 1.5rem 0 1.5rem;
      .forecast-list {
        width: 100%;
        display: flex;
        flex-direction: row;
        gap: 1.5rem;
        justify-content: space-between;
      }
      .forecast-card {
        display: flex;
        flex-direction: column;
        align-items: center;
        flex: 1;
        min-width: 100px;
        max-width: 160px;
        padding: 0rem;
        gap: 1rem;
        text-align: center;
        height: 150px;
        border-radius: 12px;
        background: rgba(255,255,255,0.13);
        box-shadow: 0 2px 8px rgba(0,0,0,0.08);
        opacity: 0;
        transform: translateY(30px);
        animation: fadeInUp 0.7s cubic-bezier(0.4,0,0.2,1) forwards;
        &.card-glass {
          opacity: 1;
        }
      }
    }
    .temperature-chart {
      position: relative;
      width: 100%;
      max-width: 700px;
      height: 300px;
      padding: 1.5rem;
      margin: 2.5rem auto 2rem auto;
      background-color: transparent;
      padding: 1.5rem 1.5rem 0 1.5rem;
      border-radius: 0 0 16px 16px;
      .chart {
        position: absolute;
        left: 0;
        top: 0;
        width: 90%;
        height: 100%;
        user-select: none;
        -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
        padding: 1.5rem; 
        margin-left: 40px;
        border-width: 0;
      }
    }
    .charts-row {
      display: flex;
      justify-content: center;
      align-items: flex-start;
      gap: 2rem;
      margin: 2rem 0 1rem 0;
      .pie-chart, .bar-chart {
        width: 320px;
        height: 260px;
        background: rgba(255,255,255,0.10);
        border-radius: 16px;
        box-shadow: 0 2px 8px rgba(0,0,0,0.08);
        padding: 1rem;
        display: flex;
        align-items: center;
        justify-content: center;
        margin: -10rem 0 1rem 0;
      }
      .chart {
        width: 100% !important;
        height: 200px !important;
      }
    }
  }
}

/* 动画关键帧和过渡 */
@keyframes fadeInUp {
  0% {
    opacity: 0;
    transform: translateY(30px);
  }
  100% {
    opacity: 1;
    transform: translateY(0);
  }
}

.fade-in {
  animation: fadeInUp 1s cubic-bezier(0.4,0,0.2,1);
}

.city-fade-enter-active, .city-fade-leave-active,
.forecast-fade-enter-active, .forecast-fade-leave-active {
  transition: all 0.6s cubic-bezier(0.4,0,0.2,1);
}
.city-fade-enter-from, .city-fade-leave-to,
.forecast-fade-enter-from, .forecast-fade-leave-to {
  opacity: 0;
  transform: translateY(30px);
}

// 天气背景动画关键帧
@keyframes weatherBg {
  0%, 100% {
    transform: scale(1) rotate(0deg);
    opacity: 0.8;
  }
  25% {
    transform: scale(1.1) rotate(1deg);
    opacity: 1;
  }
  50% {
    transform: scale(0.9) rotate(-1deg);
    opacity: 0.6;
  }
  75% {
    transform: scale(1.05) rotate(0.5deg);
    opacity: 0.9;
  }
}

// 云朵移动动画
@keyframes cloudMove {
  0% {
    left: -200px;
    opacity: 0;
  }
  10% {
    opacity: 1;
  }
  90% {
    opacity: 1;
  }
  100% {
    left: 100%;
    opacity: 0;
  }
}

// 添加雨滴效果（可选）
.container.rainy::before {
  background: 
    linear-gradient(180deg, rgba(0, 0, 0, 0.1) 0%, transparent 100%),
    radial-gradient(circle at 20% 50%, rgba(120, 119, 198, 0.3) 0%, transparent 50%),
    radial-gradient(circle at 80% 20%, rgba(255, 255, 255, 0.1) 0%, transparent 50%);
}

// 添加晴天效果（可选）
.container.sunny::before {
  background: 
    radial-gradient(circle at 30% 30%, rgba(255, 215, 0, 0.2) 0%, transparent 50%),
    radial-gradient(circle at 70% 70%, rgba(255, 255, 255, 0.15) 0%, transparent 50%);
}
</style>